/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package racesuitefx;

import DAO.RaceDAO;
import DAO.RaceResult;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.WindowEvent;
import oracle.jrockit.jfr.parser.ChunkParser;
import racesuitefx.entities.Race;

/**
 *
 * @author Wolfgang
 */
public class FXMLDocumentController implements Initializable {
    
    RaceDAO raceDao;
    private ObservableList<RaceResult> data;
    @FXML
    private TextField label;
    @FXML
    private Label gestartetLabel;
    @FXML
    private TreeView<Race> treeView;
    @FXML
    private TableView<RaceResult> resultTable;
    @FXML
    private Pane myPane;
    @FXML
    private MenuBar myBar;
    @FXML
    private AnchorPane anchorPane;
    @FXML
    private CheckBox refreshBox;
    // 
    Thread thread ;
    Node graphic  = new ImageView(new Image(getClass().getResourceAsStream("main.png")));
    //
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        raceDao = new RaceDAO();
        data = FXCollections.observableArrayList();
        buildTree();
        // fill Table with Columns base;
        TableColumn startNumber = new TableColumn("StartNummer:");
        startNumber.setCellValueFactory(new PropertyValueFactory<RaceResult, String>("startNumber"));
        
        TableColumn firstName = new TableColumn("Vorname:");
        firstName.setCellValueFactory(new PropertyValueFactory<RaceResult, String>("firstName"));
        
        TableColumn lastName = new TableColumn("Nachname:");
        lastName.setCellValueFactory(new PropertyValueFactory<RaceResult, String>("lastName"));
        
        TableColumn loopcount = new TableColumn("Runden:");
        loopcount.setCellValueFactory(new PropertyValueFactory<RaceResult, String>("loopcount"));
        
        TableColumn elapsedTime = new TableColumn("Zeit:");
        elapsedTime.setCellValueFactory(new PropertyValueFactory<RaceResult, String>("timeInMinutes"));
        
        resultTable.setItems(data);
        resultTable.getColumns().addAll(startNumber, firstName, lastName, loopcount, elapsedTime);
        resultTable.autosize();
          thread = new Thread(new Runnable() {
            public void run() {
                while(true){
                try {
                     Thread.sleep(10000);
                } catch (Exception ex) {
                    /* logging etc. */
                   ex.printStackTrace();
                }
                /* reset color here (however) */
                refresh();
                }
            }
        });
        thread.start();
        thread.suspend();
    }
    private void buildTree(){
       List<Race> races = raceDao.findAll();
       
        TreeItem<Race> parentItem = new TreeItem<Race>(new Race("Races"), graphic);
        parentItem.setExpanded(true);
        for (Race r : races) {
             TreeItem<Race> item = new TreeItem<Race>(r);
            if(r.getActive() != null && r.getActive().startsWith("1")){
             item.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("check.png"))));
            }else{
              item.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("error.png"))));
            }            
            parentItem.getChildren().add(item);
        }
        treeView.setRoot(parentItem);
        treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        final ContextMenu contextMenu = new ContextMenu();
        MenuItem item1 = new MenuItem("Rennen Starten");
        item1.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                Race r = treeView.getSelectionModel().getSelectedItem().getValue();
                raceDao.startRace(r);
                Util.CommunicateUtil.startRace(r.getRaceId());
                label.setText(r.getName());
                buildTree();
            }
        });
        MenuItem item2 = new MenuItem("Rennen Stoppen");
        item2.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                Race r = treeView.getSelectionModel().getSelectedItem().getValue();
                raceDao.stopRace(r);
                Util.CommunicateUtil.stopRace();
               label.setText(""); 
               buildTree();
            }
        });
        
        MenuItem item3 = new MenuItem("Starter");
        item3.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                try {
                    label.setVisible(false);
                    refreshBox.setVisible(false);
                    gestartetLabel.setVisible(false);
                    myPane.getChildren().clear();
                    FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLCreateStarter.fxml"));
                    myPane.getChildren().add(loader.load());
                    ((FXMLCreateStarterController) loader.getController()).setRace(treeView.getSelectionModel().getSelectedItem().getValue());
                    
                } catch (IOException ex) {
                    Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        MenuItem item4 = new MenuItem("Ergebnisse Drucken");
        item4.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent e) {
                Race r = treeView.getSelectionModel().getSelectedItem().getValue();
                Util.ReportUtil.printReport(r);
            }
        });
        contextMenu.getItems().addAll(item1, item2, item3, item4);
        treeView.setContextMenu(contextMenu);
        treeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<Race>>() {
            
            @Override
            public void changed(ObservableValue<? extends TreeItem<Race>> observable, TreeItem<Race> oldValue, TreeItem<Race> newValue) {
                label.setVisible(true);
                refreshBox.setVisible(true);
                gestartetLabel.setVisible(true);
                myPane.getChildren().clear();
                myPane.getChildren().add(resultTable);
                if(newValue != null){
                    ObservableList<RaceResult> datas = FXCollections.observableArrayList(raceDao.getResults(newValue.getValue().getRaceId()));
                    resultTable.setItems(datas);
                }
                
            }
        });
    }
    private void refresh(){
        ObservableList<RaceResult> datas = FXCollections.observableArrayList(raceDao.getResults(((Race)treeView.getSelectionModel().getSelectedItem().getValue()).getRaceId()));
        resultTable.setItems(datas);
    }
    public void tagTable() throws IOException {
        myPane.getChildren().clear();
        label.setVisible(false);
        refreshBox.setVisible(false);
        gestartetLabel.setVisible(false);
        FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLTags.fxml"));
        myPane.getChildren().add(loader.load());
        treeView.setDisable(true);
    }

    public void raceEditor() {
        myPane.getChildren().clear();
        buildTree();
        treeView.setDisable(false);
        label.setVisible(true);
        refreshBox.setVisible(true);
        gestartetLabel.setVisible(true);
    }
    public void addRace() throws IOException{
        myPane.getChildren().clear();
        label.setVisible(false);
        refreshBox.setVisible(false);
        gestartetLabel.setVisible(false);
        FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLAddRace.fxml"));
        myPane.getChildren().add(loader.load());
        treeView.setDisable(true);
    }
    
   @FXML
   public void refreshAction(){
       if(refreshBox.isSelected()){
           // start thread
       
               treeView.setDisable(true);
               this.thread.resume();
              
           
           
       }else{
           //stop thread
          
               treeView.setDisable(false);
               this.thread.suspend();
           
       }
   }

    @Override
    protected void finalize() throws Throwable {
        if(this.thread.isAlive()){
            this.thread.interrupt();
        }
        super.finalize(); //To change body of generated methods, choose Tools | Templates.
    }
   
   
    
}
